﻿Imports System.IO
Imports System.Globalization
Imports System.Reflection

Public Class Station
    Inherits AlertTarget
    Implements IDisposable


    'Public Sub New(ByVal id As String)
    '    Me.Id = id
    'End Sub

    Private _id As String = ""
    Public Property Id() As String
        Get
            Return _id
        End Get
        Set(ByVal value As String)
            _id = value
            OnPropertyChanged("Id")
        End Set
    End Property

    Public ReadOnly Property Type() As StationType
        Get
            If Me.Id.StartsWith("co") Then
                Return StationType.Community
            ElseIf Me.Id.StartsWith("ch") Then
                Return StationType.Channel
            Else
                Return StationType.None
            End If
        End Get
    End Property

    Private _isOnAir As Boolean
    Public Property IsOnAir() As Boolean
        Get
            Return _isOnAir
        End Get
        Set(ByVal value As Boolean)
            _isOnAir = value
            OnPropertyChanged("IsOnAir")
        End Set
    End Property

    Private _recentAirdate As DateTime
    Public Property RecentAirdate() As DateTime
        Get
            Return _recentAirdate
        End Get
        Set(ByVal value As DateTime)
            _recentAirdate = value
            OnPropertyChanged("RecentAirdate")
        End Set
    End Property

    Private _recentTitle As String = ""
    Public Property RecentTitle() As String
        Get
            Return _recentTitle
        End Get
        Set(ByVal value As String)
            _recentTitle = value
            OnPropertyChanged("RecentTitle")
        End Set
    End Property

    Private _name As String = ""
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
            OnPropertyChanged("Name")
        End Set
    End Property

    Public ReadOnly Property Uri() As Uri
        Get
            Select Case Me.Type
                Case StationType.Channel
                    Return New Uri(String.Format(My.Settings.ChannelUriFormat, Me.Id))
                Case Else ' StationType.Community
                    Return New Uri(String.Format(My.Settings.CommunityUriFormat, Me.Id))
            End Select
        End Get
    End Property

    Private _IconUri As Uri
    Public Property IconUri() As Uri
        Get
            Return _IconUri
            'If _IconUri Is Nothing Then
            '    Select Case Me.Type
            '        Case StationType.Channel
            '            Return New Uri("http://icon.nicovideo.jp/channel/" & Me.Id & ".jpg")
            '        Case Else ' StationType.Community
            '            Return New Uri("http://icon.nimg.jp/community/" & Me.Id & ".jpg")
            '    End Select
            'Else
            '    Return Uri
            'End If
        End Get
        Set(ByVal value As Uri)
            _IconUri = value
        End Set
    End Property


#Region "Icon"
    Private Shared _cachePath As String = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly.Location)
    Public Shared ReadOnly Property CachePath() As String
        Get
            Return _cachePath
        End Get
    End Property

    Public Shared Sub SetCachePath(ByVal path As String)
        Try
            My.Computer.FileSystem.CreateDirectory(path)
        Catch ex As IOException
            Exit Sub
        End Try
        _cachePath = path
    End Sub

    Private ReadOnly Property CachedIconPath() As String
        Get
            Return System.IO.Path.Combine(Station.CachePath, Me.Id & ".jpg")
        End Get
    End Property

    Private WithEvents WebClient As System.Net.WebClient

    Private _NeedDisplay As Boolean
    Public Property NeedDisplay() As Boolean
        Get
            Return _NeedDisplay
        End Get
        Set(ByVal value As Boolean)
            _NeedDisplay = value
            OnPropertyChanged("Icon")
        End Set
    End Property

    Private ReadOnly Property CachedIcon() As BitmapImage
        Get
            If Not NeedDisplay Then
                Return Nothing
            End If

            Dim icon As BitmapImage = Nothing
            If System.IO.File.Exists(Me.CachedIconPath) Then
                Dim info = New System.IO.FileInfo(Me.CachedIconPath)

                Try
                    icon = New BitmapImage(New Uri(Me.CachedIconPath))

                    ' 更新
                    If info.LastWriteTime.AddMinutes(30) < Now Then
                        DownloadIconAsync()
                    End If

                Catch fileNotFoundEx As System.IO.FileNotFoundException
                    ' Ignore
                Catch ex As Exception
                    ' Ignore
                End Try
            Else
                DownloadIconAsync()
            End If

            If icon Is Nothing Then
                Return Station.NoImageIcon
            Else
                Return icon
            End If
        End Get
    End Property

    Private Sub DownloadIconAsync()
        Dim uri As Uri
        Select Case Me.Type
            Case StationType.Channel
                uri = New Uri(String.Format(CultureInfo.InvariantCulture, My.Settings.ChannelIconUriFormat, Me.Id))
            Case Else ' Community
                uri = New Uri(String.Format(CultureInfo.InvariantCulture, My.Settings.CommunityIconUriFormat, Me.Id))
        End Select

        WebClient = New System.Net.WebClient
        WebClient.DownloadFileAsync(uri, Me.CachedIconPath)
    End Sub

    Private _icon As BitmapImage
    Public ReadOnly Property Icon() As ImageSource
        Get
            If _icon Is Nothing Then
                _icon = Me.CachedIcon
            End If
            Return _icon
        End Get
    End Property

    Private Shared _noImageIcoon As BitmapImage
    Private Shared ReadOnly Property NoImageIcon() As BitmapImage
        Get
            If _noImageIcoon Is Nothing Then
                Dim noimageUri = New Uri("pack://application:,,,/NamaAlert;component/noimage.jpg")
                _noImageIcoon = New BitmapImage(noimageUri)
            End If
            Return _noImageIcoon
        End Get
    End Property

    Private Sub WebClient_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles WebClient.DownloadFileCompleted

        WebClient.Dispose()
        WebClient = Nothing

        If e.Cancelled Then
            Exit Sub
        End If

        Try
            If System.IO.File.Exists(Me.CachedIconPath) Then
                Dim info = New System.IO.FileInfo(Me.CachedIconPath)
                If info.Length = 0 Then

                    Try
                        System.IO.File.Delete(Me.CachedIconPath)

                    Catch dirEx As DirectoryNotFoundException
                        ' Ignore
                    Catch ioEx As IOException
                        ' Ignore
                    Catch unauthEx As UnauthorizedAccessException
                        ' Ignore
                    End Try

                Else
                    Try
                        _icon = New BitmapImage(New Uri(Me.CachedIconPath))
                        OnPropertyChanged("Icon")
                    Catch fileNotFoundEx As System.IO.FileNotFoundException
                        ' Ignore
                    Catch ex As Exception
                        ' Ignore
                    End Try
                End If
            End If

        Catch ex As Exception
#If DEBUG Then
            Stop
#End If
        End Try

    End Sub

#End Region

    Private disposedValue As Boolean = False        ' 重複する呼び出しを検出するには

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: 他の状態を解放します (マネージ オブジェクト)。

                Try
                    If WebClient IsNot Nothing Then
                        If WebClient.IsBusy Then
                            WebClient.CancelAsync()
                        End If
                        WebClient.Dispose()
                    End If
                Catch ex As Exception
                    ' Ignore
                End Try

            End If

            ' TODO: ユーザー独自の状態を解放します (アンマネージ オブジェクト)。
            ' TODO: 大きなフィールドを null に設定します。
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
    Public Sub Dispose() Implements IDisposable.Dispose
        ' このコードを変更しないでください。クリーンアップ コードを上の Dispose(ByVal disposing As Boolean) に記述します。
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class
